<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="handleClose"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="课程名" prop="name">
        <el-input v-model="dataForm.name" placeholder="课程名"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-cascader
          v-model="categoryName"
          :options="options"
          @change="handleChange"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="课程信息" prop="info">
        <el-input v-model="dataForm.info" placeholder="课程信息"></el-input>
      </el-form-item>
      <el-form-item label="图片" prop="img">
        <single-upload
          ref="singleUpload"
          v-model="dataForm.img"
        ></single-upload>
      </el-form-item>

      <el-form-item label="授课老师" prop="teacher">
        <el-input v-model="dataForm.teacher" placeholder="授课老师"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button
        @click="
          () => {
            visible = false;
            this.clearImg();
          }
        "
        >取消</el-button
      >
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import singleUpload from "../../common/upload/single-upload.vue";
export default {
  data() {
    return {
      categoryName: [],
      options: [],
      visible: false,
      dataForm: {
        id: 0,
        name: "",
        categoryId: "",
        info: "",
        img: "",
        teacher: ""
      },
      dataRule: {
        name: [{ required: true, message: "课程名不能为空", trigger: "blur" }],
        categoryId: [
          { required: true, message: "分类id不能为空", trigger: "blur" }
        ],
        info: [
          { required: true, message: "课程信息不能为空", trigger: "blur" }
        ],
        img: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        teacher: [
          { required: true, message: "授课老师不能为空", trigger: "blur" }
        ]
      }
    };
  },
  components: {
    singleUpload
  },
  methods: {
    formatCategoryPath(parent, children) {
      let d = [];
      children.forEach(item => {
        let model = {};
        model.label = item.name;
        model.value = item.id;
        if (item.children.length > 0) {
          this.formatCategoryPath(model, item.children);
        }
        d.push(model);
      });
      parent.children = d;
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.categoryName = [];
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.options = [];
        this.$http({
          url: this.$http.adornUrl(`/web/category/get/category/list`),
          method: "get"
        }).then(({ data }) => {
          if (data && data.code === 0) {
            let res = data.data;
            let d = [];
            res.forEach(item => {
              let model = {};
              model.label = item.name;
              model.value = item.id;
              if (item.children.length > 0) {
                this.formatCategoryPath(model, item.children);
              }
              d.push(model);
            });
            this.options = d;
          }
        });

        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/web/course/info/${this.dataForm.id}`),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.course.name;
              this.dataForm.categoryId = data.course.categoryId;
              this.dataForm.info = data.course.info;
              this.dataForm.img = data.course.img;
              this.dataForm.teacher = data.course.teacher;
              // 初始化上传组件
              this.$refs.singleUpload.init(this.dataForm.img);
              this.$http({
                url: this.$http.adornUrl(
                  `/web/category/get/category/${this.dataForm.categoryId}/layer`
                ),
                method: "get"
              }).then(({ data }) => {
                if (data && data.code === 0) {
                  this.categoryName = data.data.categoryIdLayer;
                }
              });
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/web/course/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              categoryId: this.dataForm.categoryId,
              info: this.dataForm.info,
              img: this.dataForm.img,
              teacher: this.dataForm.teacher
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
      this.clearImg();
    },
    handleChange(value) {
      this.dataForm.categoryId = value[value.length - 1];
    },
    clearImg() {
      this.$refs.singleUpload.clear();
    },
    handleClose(done) {
      this.clearImg();
      done();
    }
  }
};
</script>
